
const ticketDetailController = function(HttpService, $state, $stateParams, StorageService, $scope, KindEditorService) {
  'ngInject';

  const vm = this;

  // 数据初始化
  vm.ticketId = $stateParams.id;
  vm.ticket = null;
  vm.comments = [];
  vm.internalNotes = [];
  vm.logs = [];
  vm.permissions = {};

  // 界面状态
  vm.isLoading = true;
  vm.activeTab = 'details'; // details, comments, internal_notes, logs
  vm.userRole = StorageService.session.get('user')?.role || 'user';

  // 评论相关
  vm.newComment = '';
  vm.isAddingComment = false;

  // 内部备注相关
  vm.newInternalNote = {
    note_content: '',
    note_type: 'general',
    is_pinned: false,
    visibility: 'all_internal',
    related_field: ''
  };
  vm.isAddingInternalNote = false;
  vm.editingNote = null;

  // 验证相关
  vm.verificationComment = '';
  vm.isVerifying = false;

  // 工单更新相关
  vm.editingTicket = false;
  vm.editTicketData = {};

  // KindEditor 配置
  vm.editorOptions = {
    // 评论编辑器配置
    comment: KindEditorService.presets.comment,
    // 内部备注编辑器配置
    internalNote: angular.extend({}, KindEditorService.presets.full, {
      height: '200px'
    }),
    // 解决方案编辑器配置
    resolution: angular.extend({}, KindEditorService.presets.full, {
      height: '250px'
    }),
    // 只读编辑器配置
    readonly: KindEditorService.presets.readonly
  };

  // 初始化
  vm.$onInit = function() {
    if (!vm.ticketId) {
      alert('无效的工单ID');
      $state.go('app.ticketQuery');
      return;
    }
    loadTicketDetail();
  };

  // 加载工单详情
  function loadTicketDetail() {
    vm.isLoading = true;
    HttpService.get(`/api/tickets/${vm.ticketId}`)
      .then(response => {
        if (response.success) {
          vm.ticket = response.data.ticket;
          vm.comments = response.data.comments;
          vm.internalNotes = response.data.internalNotes;
          vm.logs = response.data.logs;
          vm.permissions = response.data.permissions;
          vm.canEdit = response.data.canEdit;
          vm.canVerify = response.data.canVerify;
          vm.canAdmin = response.data.canAdmin;
        } else {
          alert('获取工单详情失败：' + response.message);
          $state.go('app.ticketQuery');
        }
      })
      .catch(error => {
        alert('获取工单详情失败：' + (error.message || '网络错误'));
        $state.go('app.ticketQuery');
      })
      .finally(() => {
        vm.isLoading = false;
      });
  }

  // Tab 控制
  vm.setActiveTab = function(tab) {
    vm.activeTab = tab;
  };

  // 权限检查
  vm.canViewInternalNotes = function() {
    return ['support', 'operator', 'administrator'].includes(vm.userRole);
  };

  vm.canAddInternalNote = function() {
    return ['support', 'operator', 'administrator'].includes(vm.userRole);
  };

  vm.canEditInternalNote = function(note) {
    const user = StorageService.session.get('user');
    return user && (
      user.id === note.user_id || 
      ['operator', 'administrator'].includes(user.role)
    );
  };

  // 工单状态和优先级显示
  vm.getStatusBadgeClass = function(status) {
    const statusClasses = {
      'pending': 'badge-warning',
      'in_progress': 'badge-info',
      'resolved': 'badge-success',
      'closed': 'badge-secondary',
      'cancelled': 'badge-danger'
    };
    return statusClasses[status] || 'badge-secondary';
  };

  vm.getPriorityBadgeClass = function(priority) {
    const priorityClasses = {
      'low': 'badge-success',
      'medium': 'badge-info',
      'high': 'badge-warning',
      'urgent': 'badge-danger'
    };
    return priorityClasses[priority] || 'badge-secondary';
  };

  // 评论管理
  vm.addComment = function() {
    if (!vm.newComment || vm.newComment.trim() === '') {
      alert('请输入评论内容');
      return;
    }

    vm.isAddingComment = true;
    HttpService.post(`/api/tickets/${vm.ticketId}/comments`, {
      comment_content: vm.newComment.trim()
    })
      .then(response => {
        if (response.success) {
          vm.comments.push(response.data);
          vm.newComment = '';
          alert('评论添加成功');
        } else {
          alert('添加评论失败：' + response.message);
        }
      })
      .catch(error => {
        alert('添加评论失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isAddingComment = false;
      });
  };

  // 内部备注管理
  vm.addInternalNote = function() {
    if (!vm.newInternalNote.note_content || vm.newInternalNote.note_content.trim() === '') {
      alert('请输入备注内容');
      return;
    }

    vm.isAddingInternalNote = true;
    HttpService.post(`/api/tickets/${vm.ticketId}/notes`, vm.newInternalNote)
      .then(response => {
        if (response.success) {
          vm.internalNotes.unshift(response.data);
          vm.resetInternalNoteForm();
          alert('内部备注添加成功');
        } else {
          alert('添加内部备注失败：' + response.message);
        }
      })
      .catch(error => {
        alert('添加内部备注失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isAddingInternalNote = false;
      });
  };

  vm.editInternalNote = function(note) {
    vm.editingNote = angular.copy(note);
  };

  vm.updateInternalNote = function() {
    if (!vm.editingNote.note_content || vm.editingNote.note_content.trim() === '') {
      alert('请输入备注内容');
      return;
    }

    HttpService.put(`/api/tickets/${vm.ticketId}/notes`, {
      noteId: vm.editingNote.id,
      note_content: vm.editingNote.note_content,
      note_type: vm.editingNote.note_type,
      is_pinned: vm.editingNote.is_pinned,
      visibility: vm.editingNote.visibility
    })
      .then(response => {
        if (response.success) {
          // 更新列表中的备注
          const index = vm.internalNotes.findIndex(n => n.id === vm.editingNote.id);
          if (index !== -1) {
            vm.internalNotes[index] = response.data;
          }
          vm.editingNote = null;
          alert('内部备注更新成功');
        } else {
          alert('更新内部备注失败：' + response.message);
        }
      })
      .catch(error => {
        alert('更新内部备注失败：' + (error.message || '网络错误'));
      });
  };

  vm.deleteInternalNote = function(note) {
    if (!confirm('确定要删除这条内部备注吗？')) {
      return;
    }

    HttpService.delete(`/api/tickets/${vm.ticketId}/notes`, {
      noteId: note.id
    })
      .then(response => {
        if (response.success) {
          // 从列表中移除
          const index = vm.internalNotes.findIndex(n => n.id === note.id);
          if (index !== -1) {
            vm.internalNotes.splice(index, 1);
          }
          alert('内部备注删除成功');
        } else {
          alert('删除内部备注失败：' + response.message);
        }
      })
      .catch(error => {
        alert('删除内部备注失败：' + (error.message || '网络错误'));
      });
  };

  vm.cancelEditInternalNote = function() {
    vm.editingNote = null;
  };

  vm.resetInternalNoteForm = function() {
    vm.newInternalNote = {
      note_content: '',
      note_type: 'general',
      is_pinned: false,
      visibility: 'all_internal',
      related_field: ''
    };
  };

  // 验证操作
  vm.approveTicket = function() {
    vm.performVerification('approve');
  };

  vm.rejectTicket = function() {
    vm.performVerification('reject');
  };

  vm.performVerification = function(action) {
    if (action === 'reject' && (!vm.verificationComment || vm.verificationComment.trim() === '')) {
      alert('驳回验证时必须提供原因');
      return;
    }

    vm.isVerifying = true;
    HttpService.post(`/api/tickets/${vm.ticketId}/verify`, {
      action: action,
      comment: vm.verificationComment.trim()
    })
      .then(response => {
        if (response.success) {
          vm.ticket.verification_status = response.data.verification_status;
          vm.ticket.status = response.data.status;
          vm.verificationComment = '';
          alert(action === 'approve' ? '验证通过' : '验证驳回');
          loadTicketDetail(); // 重新加载以获取最新状态
        } else {
          alert((action === 'approve' ? '验证通过失败：' : '验证驳回失败：') + response.message);
        }
      })
      .catch(error => {
        alert((action === 'approve' ? '验证通过失败：' : '验证驳回失败：') + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isVerifying = false;
      });
  };

  // 工单编辑
  vm.startEditTicket = function() {
    vm.editingTicket = true;
    vm.editTicketData = angular.copy(vm.ticket);
  };

  vm.saveTicketEdit = function() {
    HttpService.put(`/api/tickets/${vm.ticketId}`, vm.editTicketData)
      .then(response => {
        if (response.success) {
          vm.ticket = response.data;
          vm.editingTicket = false;
          alert('工单更新成功');
          loadTicketDetail(); // 重新加载以获取最新状态
        } else {
          alert('工单更新失败：' + response.message);
        }
      })
      .catch(error => {
        alert('工单更新失败：' + (error.message || '网络错误'));
      });
  };

  vm.cancelTicketEdit = function() {
    vm.editingTicket = false;
    vm.editTicketData = {};
  };

  // 返回工单列表
  vm.goBack = function() {
    $state.go('app.ticketQuery');
  };

  // 刷新数据
  vm.refresh = function() {
    loadTicketDetail();
  };
};

const ticketDetailComponent = {
  templateUrl: 'src/app/pages/ticket-detail/ticket-detail.template.html',
  controller: ticketDetailController
};

function initTicketDetailController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化工单详情控制器模块');
    return;
  }

  angular.module('app.pages.ticketDetail', [])
    .component('ticketDetailPage', ticketDetailComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initTicketDetailController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initTicketDetailController();
}